from django.db import models

class Stock(models.Model):
    symbol = models.CharField(max_length=10, primary_key=True)
    name = models.TextField(blank=True, null=True)

    class Meta:
        db_table = 'stocks'
        managed = False
        ordering = ['symbol']

    def __str__(self):
        return f"{self.symbol} - {self.name}"

class StockDetail(models.Model):
    symbol = models.CharField(max_length=10, primary_key=True)
    org_name_cn = models.TextField(blank=True, null=True)
    org_short_name_cn = models.TextField(blank=True, null=True)
    main_operation_business = models.TextField(blank=True, null=True)
    legal_representative = models.TextField(blank=True, null=True)
    general_manager = models.TextField(blank=True, null=True)
    established_date = models.BigIntegerField(blank=True, null=True)
    reg_asset = models.FloatField(blank=True, null=True)
    staff_num = models.IntegerField(blank=True, null=True)
    telephone = models.TextField(blank=True, null=True)
    email = models.TextField(blank=True, null=True)
    org_website = models.TextField(blank=True, null=True)
    reg_address_cn = models.TextField(blank=True, null=True)
    office_address_cn = models.TextField(blank=True, null=True)
    listed_date = models.BigIntegerField(blank=True, null=True)
    provincial_name = models.TextField(blank=True, null=True)
    actual_controller = models.TextField(blank=True, null=True)
    chairman = models.TextField(blank=True, null=True)
    update_time = models.DateTimeField(blank=True, null=True)

    class Meta:
        db_table = 'stock_individual_basic_info_xq'
        managed = False

    def __str__(self):
        return f"{self.symbol} - {self.org_short_name_cn}"

class DailyData(models.Model):
    id = models.IntegerField(primary_key=True)
    symbol = models.CharField(max_length=10, blank=True, null=True)
    trade_date = models.DateField(blank=True, null=True)
    open = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    close = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    high = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    low = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    volume = models.BigIntegerField(blank=True, null=True)
    amount = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
    price_amplitude = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True)
    change_pct = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True)
    change_amount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    turnover_rate = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True)

    class Meta:
        managed = False
        ordering = ['-trade_date']

    def __str__(self):
        return f"{self.symbol} - {self.trade_date}"

class FinancialIndicatorManager(models.Manager):
    def get_queryset(self):
        # 使用raw SQL查询避免Django自动添加id字段
        return super().get_queryset().raw("""
            SELECT 
                stock_code || '-' || date::text as id,
                stock_code, date, diluted_eps, weighted_eps, roe, 
                net_profit_margin_on_sales, gross_profit_margin, asset_liability_ratio,
                current_ratio, quick_ratio, total_assets, 
                main_business_income_growth_rate, net_profit_growth_rate
            FROM stock_financial_analysis_indicator
        """)

class FinancialIndicator(models.Model):
    stock_code = models.CharField(max_length=10)
    date = models.DateField()
    diluted_eps = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    weighted_eps = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    roe = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True)
    net_profit_margin_on_sales = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True)
    gross_profit_margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True)
    asset_liability_ratio = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True)
    current_ratio = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True)
    quick_ratio = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True)
    total_assets = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
    main_business_income_growth_rate = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True)
    net_profit_growth_rate = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True)

    objects = FinancialIndicatorManager()

    class Meta:
        db_table = 'stock_financial_analysis_indicator'
        managed = False
        ordering = ['-date']
        unique_together = [['stock_code', 'date']]

    def __str__(self):
        return f"{self.stock_code} - {self.date}"

class Strategy(models.Model):
    STRATEGY_TYPES = [
        ('ma', '移动平均线策略'),
        ('rsi', 'RSI超卖策略'),
        ('macd', 'MACD金叉策略'),
        ('boll', '布林带策略'),
        ('pe', '低市盈率策略'),
        ('dividend', '高股息率策略'),
        ('roe', '高ROE策略'),
        ('volume', '成交量突破策略'),
        ('kdj', 'KDJ指标策略'),
        ('multi_ma', '均线多头排列策略'),
        ('break_high', '突破前高策略'),
        ('money_flow', '资金流向策略'),
    ]
    
    name = models.CharField(max_length=100, verbose_name='策略名称')
    strategy_type = models.CharField(max_length=20, choices=STRATEGY_TYPES, verbose_name='策略类型')
    description = models.TextField(blank=True, null=True, verbose_name='策略描述')
    parameters = models.JSONField(default=dict, verbose_name='策略参数')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        managed = True  # 让Django自动管理数据库表
        db_table = 'strategy'
        verbose_name = '交易策略'
        verbose_name_plural = '交易策略'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.name} ({self.get_strategy_type_display()})"

class BuySignal(models.Model):
    strategy = models.ForeignKey(Strategy, on_delete=models.CASCADE, verbose_name='策略', default=1)
    stock = models.CharField(max_length=10, verbose_name='股票代码', default='')
    signal_date = models.DateField(verbose_name='信号日期')
    signal_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='信号价格')
    signal_strength = models.DecimalField(max_digits=5, decimal_places=2, default=0, verbose_name='信号强度')
    reason = models.TextField(blank=True, null=True, verbose_name='买入理由')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        managed = True  # 让Django自动管理数据库表
        db_table = 'buy_signal'
        verbose_name = '买入信号'
        verbose_name_plural = '买入信号'
        ordering = ['-signal_date', '-signal_strength']
        indexes = [
            models.Index(fields=['signal_date', 'strategy']),
            models.Index(fields=['stock', 'signal_date']),
        ]

    def __str__(self):
        # 避免跨数据库关联查询，直接使用存储的字段值
        return f"BuySignal (ID: {self.id})"
